package com.hc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.common.bean.PageBean;
import com.hc.constant.OrderConst;
import com.hc.constant.UserConst;
import com.hc.domain.Cart;
import com.hc.domain.CartItem;
import com.hc.domain.Order;
import com.hc.domain.OrderItem;
import com.hc.domain.Pay;
import com.hc.domain.ReceiveAddr;
import com.hc.domain.Sku;
import com.hc.domain.User;
import com.hc.mapper.OrderMapper;
import com.hc.res.OrderRes;
import com.hc.res.SkuItem;
import com.hc.service.CartItemService;
import com.hc.service.CartService;
import com.hc.service.OrderItemService;
import com.hc.service.OrderService;
import com.hc.service.PayService;
import com.hc.service.ReceiveAddrService;
import com.hc.service.SkuService;
import com.hc.trans.SkuTrans;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hecai
 * @date 2021/12/20 9:51
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Resource
    private CartService cartService;
    @Resource
    private CartItemService cartItemService;
    @Resource
    private OrderItemService orderItemService;

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public boolean buy(Long addId, Integer payType, List<Integer> skuIds) {
        User user = UserConst.user;
        Pay pay = Pay.builder().type(payType).build();

        Cart cart = cartService.getOne(new QueryWrapper<Cart>().eq("user_id", user.getId()));

        Order order = Order.builder()
                .receiveAddrId(addId)
                .payId(pay.getId())

                .userId(user.getId())
                .status(OrderConst.Status.DAI_ZHI_FU)
                .build();
        //将订单保存到数据库
        baseMapper.insert(order);

        Integer totalAmount = 0;
        BigDecimal totalMoney = BigDecimal.ZERO;

        //待删除的OrderItem的id的集合
        List<CartItem> cartItemList = cartItemService.list(new QueryWrapper<CartItem>().eq("cart_id", cart.getId()));
        for (CartItem cartItem : cartItemList) {
            //如果用户提交的cartIterm在skuIds中
            if (skuIds.contains(cartItem.getId())) {
                //1、将CartItem移动到OrderItem中
                OrderItem orderItem = OrderItem.builder()
                        .amount(cartItem.getAmount())
                        .money(cartItem.getMoney())
                        .orderId(order.getId())
                        .skuId(cartItem.getSkuId())
                        .build();
                orderItemService.save(orderItem);

                totalMoney = totalMoney.add(cartItem.getMoney());
                totalAmount += cartItem.getAmount();
                //2、将CartItem删除
                cartItemService.removeById(cartItem.getId());
            }
        }

        //修改Cart
        cart.setTotalAmount(cart.getTotalAmount() - totalAmount);
        cart.setTotalMoney(cart.getTotalMoney().subtract(totalMoney));
        cartService.updateById(cart);

        //更新Order的总金额
        order.setTotalMoney(totalMoney);
        baseMapper.updateById(order);
        return true;
    }


    @Resource
    private PayService payService;

    @Resource
    private ReceiveAddrService receiveAddrService;

    @Resource
    private SkuService skuService;

    @Override
    public PageBean<OrderRes> getOrderByUserId(Integer userId, Integer status, Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        baseMapper.selectPage(page, new QueryWrapper<Order>()
                .select("id", "total_money", "pay_id", "receive_addr_id", "status", "create_time")
                .eq("user_id", userId)
                .orderByDesc("create_time")
                .eq("status", status));

        List<OrderRes> orderResList = new ArrayList<>();

        for (Order order : page.getRecords()) {
            OrderRes orderRes = new OrderRes();
            orderRes.setId(order.getId());
            orderRes.setTotalMoney(order.getTotalMoney());
            orderRes.setStatus(order.getStatus());
            orderRes.setCreateTime(order.getCreateTime());


            Pay pay = payService.getOne(new QueryWrapper<Pay>().select("type").eq("id", order.getPayId()));
            Integer payType = pay.getType();
            orderRes.setPayType(payType);

            ReceiveAddr receiveAddr = receiveAddrService.getOne(new QueryWrapper<ReceiveAddr>()
                    .select("id", "receiver")
                    .eq("id", order.getReceiveAddrId()));

            orderRes.setReceiveAddrId(receiveAddr.getId());
            orderRes.setReceiver(receiveAddr.getReceiver());

            List<SkuItem> skuItemList = new ArrayList<>();
            List<OrderItem> orderItemList = orderItemService.list(new QueryWrapper<OrderItem>()
                    .select("sku_id", "amount")
                    .eq("order_id", order.getId()));
            for (OrderItem orderItem : orderItemList) {
                Sku sku = skuService.getOne(new QueryWrapper<Sku>()
                        .select("id", "name", "specs", "price1", "price2", "img")
                        .eq("id", orderItem.getSkuId()));
                SkuItem skuItem = SkuTrans.MAPPER.sku2skuItem(sku);
                skuItemList.add(skuItem);
            }
            orderRes.setSkuItemList(skuItemList);
            orderResList.add(orderRes);
        }

        PageBean<OrderRes> pageBean = new PageBean<>();
        pageBean.setPageSize((int) page.getSize());
        pageBean.setCurrent(page.getCurrent());
        pageBean.setPages(page.getPages());
        pageBean.setRecords(orderResList);
        return pageBean;
    }

}


